<template>
  <el-card style="margin-bottom:20px;">
    <div ref="container" class="container">
      <canvas ref="canvas" />
      <div ref="control" class="control-ops control">
        <el-button type="info" @click="onClear">清 空</el-button>
        <el-button type="primary" @click="onConfirm">确 认</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserSign',
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          userId: undefined,
          signature: undefined
        }
      }
    }
  },
  data() {
    return {
      width: 0,
      height: 0,
      lastX: 0,
      lastY: 0,
      initialized: false,
      signature: ''
    }
  },
  mounted() {
    this.$nextTick(this.loadForm)
  },
  methods: {
    loadForm() {
      this.signature = ''
      this.$http.get('/admin/system/user/loadForm', {
        params: {
          id: this.user.userId
        }
      }).then(response => {
        if (response.param.signature) {
          this.signature = response.param.signature
        }
        this.init()
      }).catch(() => {})
    },
    init() {
      let mousePressed = false
      const container = this.$refs.container
      this.width = container.offsetWidth
      this.height = container.offsetHeight < 300 ? 300 : container.offsetHeight
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')

      container.setAttribute('width', this.width + 'px')
      container.setAttribute('height', this.height + 'px')
      canvas.setAttribute('width', this.width + 'px')
      canvas.setAttribute('height', this.height + 'px')

      ctx.moveTo(0, 0)
      ctx.fillStyle = '#ddd'
      ctx.fillRect(0, 0, this.width, this.height)
      // const control = this.$refs.control

      const vm = this
      if (this.signature) {
        // 绘图
        const img = new Image()
        img.src = this.signature
        ctx.drawImage(img, 0, 0, this.width, this.height)
      }

      // 触摸屏
      canvas.addEventListener(
        'touchstart',
        function(event) {
          if (event.targetTouches.length === 1) {
            event.preventDefault() // 阻止浏览器默认事件，重要
            const touch = event.targetTouches[0]
            mousePressed = true
            vm.draw(
              touch.offsetLeft,
              touch.offsetTop,
              false
            )
          }
        },
        false
      )

      canvas.addEventListener(
        'touchmove',
        function(event) {
          if (event.targetTouches.length === 1) {
            event.preventDefault() // 阻止浏览器默认事件，重要
            const touch = event.targetTouches[0]
            if (mousePressed) {
              vm.draw(
                touch.offsetLeft,
                touch.offsetTop,
                true
              )
            }
          }
        },
        false
      )

      canvas.addEventListener(
        'touchend',
        function(event) {
          if (event.targetTouches.length === 1) {
            event.preventDefault() // 阻止浏览器默认事件，防止手写的时候拖动屏幕，重要
            mousePressed = false
          }
        },
        false
      )

      // 鼠标
      canvas.onmousedown = function(event) {
        mousePressed = true
        vm.draw(
          event.offsetX,
          event.offsetY,
          false
        )
      }

      canvas.onmousemove = function(event) {
        if (mousePressed) {
          vm.draw(
            event.offsetX,
            event.offsetY,
            true
          )
        }
      }

      canvas.onmouseup = function(event) {
        mousePressed = false
      }
    },
    draw(x, y, isDown) {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')

      if (isDown) {
        ctx.beginPath()
        ctx.strokeStyle = '#666' // 颜色
        ctx.lineWidth = 3 // 线宽
        ctx.lineJoin = 'round'
        ctx.moveTo(this.lastX, this.lastY)
        ctx.lineTo(x, y)
        ctx.closePath()
        ctx.stroke()
      }
      this.lastX = x
      this.lastY = y
    },
    onConfirm() {
      const canvas = this.$refs.canvas
      // const ctx = canvas.getContext('2d')
      this.imageUrl = canvas.toDataURL('image/png') // 得到生成后的签名base64数据
      this.save(this.imageUrl)
    },
    save(blob) {
      this.$http.post('/admin/system/user/updateInfo', {
        userId: this.user.userId,
        signature: blob
      }).then(response => {
        this.$message({
          type: 'success',
          message: response.msg
        })
      }).catch(() => {})
    },
    onClear() {
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      ctx.setTransform(1, 0, 0, 1, 0, 0)
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    }
  }
}
</script>

<style lang="scss" scoped>
canvas {
  background: #ddd;
}

.container {
  position: relative;
}
.control {
  padding: 15px 0;
  box-sizing: border-box;
  position: absolute;
  bottom: 0;
  text-align: center;
  background: #fff;
}

@media screen and (orientation: portrait) {
  .control {
    height: 80px;
    left: 40px;
    top: 0;
    transform: rotate(90deg);
    transform-origin: left top;
    width: 100vh;
  }
}
@media screen and (orientation: landscape) {
  .control {
    left: 0;
    width: 100%;
  }
}
</style>
